package com.example.demo.Filter.JWTInterceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.Entity.Ip_Table.IpTable;
import com.example.demo.ServiceImpl.Ip_Table.IpTableServiceImpl;
import com.example.demo.Utils.IpUtils.IpUtil;
import com.example.demo.Utils.JWTUtils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class JWTInterceptors implements HandlerInterceptor {
    @Resource
    IpTableServiceImpl ipTbService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader("Authorization");
        String Ip = IpUtil.getIpAddress(request);
        String path = request.getRequestURI();
        if (token == null) {
            log.error("此次请求没有权限:Ip为{}", Ip);
            map.put("state", false);
            map.put("msg", "无法访问");
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return false;
        }
        try {
            IpTable saveIpTable = new IpTable(null, Ip, 0, path, new Date());
            // 验证令牌
            JWTUtils.verify(token);
            // 放行请求
            LambdaQueryWrapper<IpTable> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(IpTable::getIpAddress, Ip);
            List<IpTable> ipTable = ipTbService.list(queryWrapper);
            if (ipTable != null&& !ipTable.isEmpty()) {
                saveIpTable.setIsBlack(ipTable.get(0).getIsBlack());
            }
            ipTbService.save(saveIpTable);
            log.info("请求的已通过IP为{}", Ip);
            return true;  // 放行请求

        } catch (SignatureVerificationException e) {
            log.error(e.getMessage());
            map.put("msg", "无效签名！");
        } catch (TokenExpiredException e) {
            log.error(e.getMessage());
            map.put("msg", "token过期");
        } catch (AlgorithmMismatchException e) {
            log.error(e.getMessage());
            map.put("msg", "算法不一致");
        } catch (Exception e) {
            log.error(e.getMessage());
            map.put("msg", "token无效！");
        }
        map.put("state", false);  // 设置状态
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        log.error("此次请求被拦截:Ip为{}", Ip);
        log.error("请求的资源为{}", path);
        return false;
    }
}
